const net = require('net')
const getEnquire = require('./getEnquire')

class UserSchedule {

    constructor(config = {}) {
        config.ip = config.ip ? config.ip : '127.0.0.1'
        const { ip, port } = config
        this.tcpClient = net.connect(port, ip)
        this.deviceIdSchedulePool = {}
    }
    //设置定时任务 传入time:执行间隔 len:寄存器长度（数据点个数）
    setUserSchedule(config = {}) {
        config.slaverSchedule = config.slaverSchedule ? config.slaverSchedule : []
        const { deviceId, slaverIndex, plc, time, len } = config
        const result = this.cancelDeviceSlaverSchedule(config)
        const writeData = '9901' + deviceId + getEnquire(slaverIndex, plc, { len })
        const intervalId = setInterval(() => {
            this.tcpClient.write(writeData)
        }, time);
        //存入设备从机定时任务
        this.deviceIdSchedulePool[deviceId + slaverIndex]
            ? this.deviceIdSchedulePool[deviceId + slaverIndex].push(intervalId)
            : this.deviceIdSchedulePool[deviceId + slaverIndex] = [intervalId]


        return result
    }
    //清除设备从机所有定时任务 传入设备id和从机
    cancelDeviceSlaverSchedule(config = {}) {
        const { deviceId, slaverIndex } = config
        if (this.deviceIdSchedulePool[deviceId + slaverIndex]) {
            this.deviceIdSchedulePool[deviceId + slaverIndex].forEach(element => {
                clearInterval(element)
            });
            delete this.deviceIdSchedulePool[deviceId + slaverIndex]
            return { status: 0, data: { modify: 1 } }
        };
        return { status: 0, data: { modify: 0 } }
    }

    cancelDeviceSchedule(config = {}) {
        config.slaverLength = config.slaverLength || 1;
        const { deviceId, slaverLength } = config
        let num = 0;
        if(!deviceId){
            return{status:1,data:{'!deviceId':'true'}}
        }

        for (let i = 1; i < slaverLength*1+1; i++) {
            if (this.deviceIdSchedulePool[deviceId + i]) {
                this.deviceIdSchedulePool[deviceId + i].forEach(element => {
                    clearInterval(element)
                    num++
                });
                delete this.deviceIdSchedulePool[deviceId + i]
            }
            
        }
        return { status: 0, data: { remove:num } }

    }
}


const setSchedule = new UserSchedule({ port: 15000 })

module.exports = setSchedule